<template>
    <div>
        <template v-if="uploadStyle=='image'">
            <div class="demo-upload-list" v-for="(item,index) in uploadList" :key="index">
                <template v-if="item.status === 'finished'">
                    <img :src="item.url">
                    <div class="demo-upload-list-cover">
                        <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                        <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                    </div>
                </template>
                <template v-else>
                    <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                </template>
            </div>
        </template>
        <template v-else>
            <div v-for="(item,index) in uploadList" :key="index">
                <template v-if="item.status === 'finished'">
                    {{item.name}}
                    <Icon type="ios-eye-outline" size="24" style="cursor:pointer"
                          @click.native="openWinUrl(item)"></Icon>
                    <Icon type="ios-trash-outline" size="24" style="cursor:pointer"
                          @click.native="handleRemove(item)"></Icon>
                </template>
                <template v-else>
                    <Progress v-if="item.showProgress" :percent="item.percentage" hide-info
                              style="width: 300px;"></Progress>
                </template>
            </div>
        </template>
        <Upload
                ref="upload"
                :show-upload-list="false"
                :default-file-list="getDefaultList"
                :on-success="handleSuccess"
                :format="format"
                :max-size="maxSize"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                :before-upload="handleBeforeUpload"
                multiple
                :data="params"
                type="drag"
                :action="uploadUrl"
                v-show="clickImgShow"
                style="display: inline-block;">
            <div :class="{'select-style':uploadStyle=='image', 'other-style':uploadStyle!='image'}">
                <Icon v-if="uploadStyle=='image'" type="ios-camera" size="20"></Icon>
                <Icon v-else type="ios-cloud-upload-outline" size="20"></Icon>
            </div>
        </Upload>
        <Modal title="查看图片" v-model="visible">
            <img :src="imgName.url" v-if="visible" style="width: 100%">
        </Modal>
    </div>
</template>
<script>
import { getOssSign, uploadPic } from '../../api/sys'
import md5 from 'js-md5'

export default {
  name: 'WlUploadOssFiles',
  props: {
    defaultStringList: {
      type: String,
      default: () => {
        return ''
      }
    },
    maxNum: {
      type: Number,
      default: () => {
        return 5
      }
    },
    options: {
      type: Object,
      default: () => {
        return {
          oneDir: 'upload',
          twoDir: 'wl',
          ip: 'https://qstb.mzj.shenyang.gov.cn',
          url: ''
        }
      }
    },
    maxNumMessage: {
      type: String,
      default: () => {
        return ''
      }
    },
    maxSize: {
      type: Number,
      default: () => {
        return 3072
      }
    },
    format: {
      type: Array,
      default: () => {
        return ['jpg', 'jpeg', 'png', 'csv']
      }
    },
    uploadStyle: {
      type: String,
      default: () => {
        return 'image'
      }
    },
    resultFiltration: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    uploadUrl: {
      type: String,
      default: () => {
        return 'http://house.wanglanglang.com'
      }
    },
    fileName: {
      type: String,
      default: () => {
        return 'md5'
      }
    },
    rootDir: {
      type: String,
      default: () => {
        return 'house'
      }
    },
    fileDir: {
      type: String,
      default: () => {
        return '/Wl/'
      }
    },
    uploadType: {
      type: String,
      default: () => {
        return 'oss' // --oss,php,java
      }
    }
  },
  model: {
    prop: 'defaultStringList',
    event: 'change'
  },
  computed: {
    showMaxNumMessage () {
      if (this.maxNumMessage === '') {
        return '最多上传' + this.maxNum + '张图片'
      } else {
        return this.maxNumMessage
      }
    },
    count () {
      return this.uploadList.length
    },
    clickImgShow () {
      if (this.maxNum === this.uploadList.length) {
        return false
      }
      return true
    },
    getDefaultList () {
      if (this.defaultStringList !== '') {
        let list = this.defaultStringList.split(',')
        let data = []
        list.forEach((item, index) => {
          if (item !== '') {
            data.push({ name: index, url: item })
          }
        })
        return data
      }
      return []
    }
  },
  data () {
    return {
      imgName: '',
      visible: false,
      uploadList: [],
      params: {},
      fileType: 'image/png',
      fileSuffix: 'png',
      uidList: [],
      upPicData: {
        file: '',
        filePath: '',
        fileName: ''
      }
    }
  },
  methods: {
    handleView (name) {
      this.imgName = name
      this.visible = true
    },
    handleRemove (file) {
      const fileList = this.$refs.upload.fileList
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1)
      this.uploadList = this.$refs.upload.fileList
      this.resultAction(this.$refs.upload.fileList)
    },
    handleSuccess (res, file, fileList) {
      this.uploadList = this.$refs.upload.fileList
      if (this.uploadType === 'oss') {
        this.uploadList.forEach((item, index) => {
          if (!item.url) {
            item.url = this.uploadUrl + '/' + this.rootDir + '/' + this.fileType + this.fileDir + this.fileName + index + '.' + this.fileSuffix
            item.showProgress = false
            item.percentage = 100
            item.status = 'finished'
            return false
          }
        })
        this.resultAction(this.$refs.upload.fileList)
      } else if (this.uploadType === 'php') {
        let runResult = true
        this.uploadList.forEach((item, index) => {
          if (item.response) {
            if (item.response.errcode === 1001) {
              if (item.response.data.url) {
                item.url = item.response.data.url
              }
            } else {
              this.$refs.upload.fileList.splice(index, 1)
              // this.uploadList = this.$refs.upload.fileList
              this.$Message.error(item.response.errmsg)
            }
          } else {
            runResult = false
          }
        })
        if (runResult) {
          this.resultAction(this.$refs.upload.fileList)
        }
      }
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: '文件格式 ' + file.name + ' 不正确,请选择' + this.format.join(',')
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件  ' + file.name + ' 太大，不能超过' + parseInt(this.maxSize / 1000) + 'M'
      })
    },
    handleBeforeUpload (file) {
      const check = this.uploadList.length < this.maxNum
      let arr = file.type.split('/')
      this.fileSuffix = arr[1]
      this.fileType = file.type
      let filePath = this.rootDir + '/' + this.fileType + this.fileDir + this.fileName + this.count + '.' + this.fileSuffix
      if (!check) {
        this.$Notice.warning({
          title: this.showMaxNumMessage
        })
      } else if (this.uploadType === 'oss') {
        this.params.key = filePath
      } else if (this.uploadType === 'hadoop') {
        let _this = this
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          let index = reader.result.indexOf('base64,') + 7
          _this.upPicData.file = reader.result.substring(index)
          _this.upPicData.filePath = _this.rootDir + '/' + _this.fileDir
          if (_this.fileName === 'md5') {
            _this.upPicData.fileName = md5(_this.upPicData.file) + '.' + this.fileSuffix
          } else {
            _this.upPicData.fileName = _this.fileName + '.' + this.fileSuffix
          }
          _this.useJavaUpImg()
        }
        return false
      }
      return check
    },
    openWinUrl (item) {
      window.open(item.url)
    },
    clear () {
      this.$refs.upload.clearFiles()
      this.uploadList = this.$refs.upload.fileList
    },
    useJavaUpImg () {
      this.uploadList.push({
        status: 'begin',
        url: '',
        showProgress: true,
        percentage: 90
      })
      let count = this.uploadList.length - 1
      uploadPic(this.upPicData, '', this.uploadUrl).then(ret => {
        if (ret.data.errcode === '0') {
          this.uploadList[count].url = ret.data.data
          this.uploadList[count].showProgress = false
          this.uploadList[count].percentage = 100
          this.uploadList[count].status = 'finished'
        } else {
          this.uploadList.splice(count, 1)
          this.$Message.error('上传失败')
        }
        this.resultAction(this.uploadList)
      })
    },
    resultAction (data) {
      let result = data
      if (this.resultFiltration) {
        result = ''
        if (data.length > 0) {
          if (this.maxNum > 1) {
            data.forEach(item => {
              result += item.url + ','
            })
          } else {
            result = data[0].url
          }
        }
      }
      this.$emit('change', result)
      this.$emit('result', result)
    }
  },
  mounted () {
    this.uploadList = this.$refs.upload.fileList
    if (this.uploadType === 'oss') {
      getOssSign({ dir: this.rootDir }).then(ret => {
        if (ret.data.errcode === 1001) {
          let option = ret.data.data
          this.params = {
            policy: option.policy,
            OSSAccessKeyId: option.accessid,
            success_action_status: 200,
            signature: option.signature
          }
        }
      })
    }
  },
  watch: {
    defaultStringList (data) {
      this.$nextTick(() => {
        this.uploadList = this.$refs.upload.fileList
      })
    }
  }
}
</script>
<style>
    .demo-upload-list {

    }

    .demo-upload-list img {
        /*width: 100%;*/
        /*height: 100%;*/
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
        margin-right: 4px;
    }

    .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .6);
    }

    .demo-upload-list:hover .demo-upload-list-cover {
        display: block;
    }

    .demo-upload-list-cover i {
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }

    .demo-upload-list .file {
        background-color: red;
        width: 300px;
    }

    .select-style {
        width: 58px;
        height: 58px;
        line-height: 58px;
    }

    .other-style {
        /*width:200px;*/
        /*height:30px;*/
        padding: 5px 30px;
        color: #666;
    }
</style>
